package com.jdrx.ocp.utils;

import com.google.common.collect.Maps;
import com.jdrx.ocp.beans.commons.BusinessConstants;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.sw.sewage.service.common.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Random;

@Component
public class ValidateUtils {
    private Logger logger = LoggerFactory.getLogger(ValidateUtils.class);

    @Autowired
    RedisService redisService;

    private static int w = 70;
    private static int h = 26;

    public void createImage(HttpServletRequest request,
                            HttpServletResponse response, String uniqueId) throws IOException {

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        /*
         * 得到参数高，宽，都为数字时，则使用设置高宽，否则使用默认值
         */
       /* String width = request.getParameter("width");
        String height = request.getParameter("height");
        if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
            w = NumberUtils.toInt(width);
            h = NumberUtils.toInt(height);
        }
        */

        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        /*
         * 生成背景
         */
        createBackground(g);

        /*
         * 生成字符
         */
        String s = createCharacter(g, uniqueId);
        //request.getSession().setAttribute(BusinessConstants.VALIDATE_CODE, s);

        g.dispose();
        OutputStream out = response.getOutputStream();
        ImageIO.write(image, "JPEG", out);
        out.flush();
        out.close();

    }

    private Color getRandColor(int fc, int bc) {
        int f = fc;
        int b = bc;
        Random random = new Random();
        if (f > 255) {
            f = 255;
        }
        if (b > 255) {
            b = 255;
        }
        return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
    }

    private void createBackground(Graphics g) {
        // 填充背景
        g.setColor(getRandColor(220, 250));
        g.fillRect(0, 0, w, h);
        // 加入干扰线条
        for (int i = 0; i < 8; i++) {
            g.setColor(getRandColor(40, 150));
            Random random = new Random();
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int x1 = random.nextInt(w);
            int y1 = random.nextInt(h);
            g.drawLine(x, y, x1, y1);
        }
    }

    private String createCharacter(Graphics g, String uniqueId) {
        char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
                'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
        String[] fontTypes = {"Arial", "Arial Black", "AvantGarde Bk BT", "Calibri"};
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        StringBuilder generatedValidateCode = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
            g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
            g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD, 26));
            g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
//			g.drawString(r, i*w/4, h-5);
            s.append(r);
            generatedValidateCode.append(r);
        }
        setValidateCode(uniqueId, generatedValidateCode.toString());
        return s.toString();
    }

    /**
     * 是否是验证码登录
     *
     * @param uniqueId 浏览器唯一码
     * @param isFail   计数加1
     * @param clean    计数清零
     * @return
     */
    @SuppressWarnings("unchecked")
    public boolean isValidateCodeLogin(String uniqueId, boolean isFail, boolean clean) {

        Map<String, String> loginFailMap = (Map<String, String>) redisService.getMap(BusinessConstants.UNIQUE_ID_PREFIX + uniqueId);
        if (loginFailMap == null) {
            loginFailMap = Maps.newHashMap();
        }
        String loginFailNum = loginFailMap.get(BusinessConstants.VALIDATE_TIMES);
        Integer loginFailInteger = null;
        if (loginFailNum == null) {
            loginFailInteger = 0;
        } else {
            loginFailInteger = Integer.valueOf(loginFailNum);
        }
        if (isFail) {
            loginFailInteger++;
            loginFailMap.put(BusinessConstants.VALIDATE_TIMES, loginFailInteger.toString());
        }
        if (clean) {
            redisService.del(BusinessConstants.UNIQUE_ID_PREFIX + uniqueId);
        } else {
            redisService.setMap(BusinessConstants.UNIQUE_ID_PREFIX + uniqueId, loginFailMap, null);
        }
//        return loginFailInteger >= 5;
        return loginFailInteger >= 10;
    }

    /**
     * 设置验证码到redis
     * @param uniqueId
     * @param validateCode
     */
    public void setValidateCode(String uniqueId, String validateCode) {
        Map<String, String> loginFailMap = (Map<String, String>) redisService.getMap(BusinessConstants.UNIQUE_ID_PREFIX + uniqueId);
        if (loginFailMap != null) {
            loginFailMap.put(BusinessConstants.VALIDATE_CODE, validateCode);
            redisService.setMap(BusinessConstants.UNIQUE_ID_PREFIX + uniqueId, loginFailMap, 300L);
        }
    }

    public Boolean validateCodeRight(String uniqueId, String validateCode) {
        Map<String, String> loginFailMap = (Map<String, String>) redisService.getMap(BusinessConstants.UNIQUE_ID_PREFIX + uniqueId);
        if (loginFailMap != null) {
            String va = loginFailMap.get(BusinessConstants.VALIDATE_CODE);
            if (va != null) {
                return validateCode.toLowerCase().equals(va.toLowerCase());
            }
        }
        return false;
    }

    /**
     * 获取验证码
     * @param uniqueId
     * @throws IOException
     */
    public String getValidateCode(String uniqueId) throws BizException {
        try {
            char[] codeSeq = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
            Random random = new Random();
            StringBuilder s = new StringBuilder();
            StringBuilder generatedValidateCode = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
                s.append(r);
                generatedValidateCode.append(r);
            }
            //设置验证码到redis
            setValidateCodeToRedis(uniqueId, generatedValidateCode.toString());
            return s.toString();
        }catch (Exception e){
            logger.error(e.getMessage());
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 设置验证码到redis
     * 15分钟过期
     * @param uniqueId
     * @param validateCode
     */
    public void setValidateCodeToRedis(String uniqueId, String validateCode) throws BizException {
        try {
            redisService.set(uniqueId, validateCode, 900L);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            throw new BizException(e.getMessage());
        }
    }



}
